//
//  WBPictureView.swift
//  微博
//
//  Created by lipengfei on 15/9/9.
//  Copyright © 2015年 lipengfei. All rights reserved.
//

import UIKit
import SDWebImage

let WBStatusPictureViewCellID = "WBStatusPictureViewCellID"
class WBPictureView: UICollectionView {
    /// 数据模型
    var statusViewModel:WBStatusViewModel?{
        didSet{
            sizeToFit()
            reloadData()
        }
    }
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    ///  计算配图的高度
    private func calcViewSize () ->CGSize{
    
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        // 获取一个微博中图片的数量
        let count = statusViewModel?.thumbnailURLs?.count ?? 0
        if count == 0{
            return CGSizeZero
        }
        if count == 1{
            // 当图片的个数为1的时候，对图片进行单独的处理
            // 单个的图片等比例显示的
            // 定义一个图片的默认大小
            var size = CGSize(width: 150, height: 150)
            // 确保图片被正确的缓存
            // key 是url的完整字符窜
            let key = statusViewModel!.thumbnailURLs![0].absoluteString
            // SDWebImage 缓存的图片的名字是url的MD5值，SDWebimage 中cache文件的176行
            // 通过key（url）去缓存文件中，获取图片
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                // 设置图片的大小
                size = image.size
            }
            // 有的微博的图片是非常长的长图，所以，需要对过宽或者过窄的图片进行处理
            // 如果图片的宽度，小于40 ，那么图片的宽度以40 作为宽度， 否则以自身的宽度
            size.width = size.width < 40 ? 40 : size.width
            // 如果图片宽度大于300的时候，设置宽度为300
            size.width = size.width > 300 ? 300 : size.width
            
            layout.itemSize = size
            return size
        }
        if count == 4{
            let w = 2 * WBStatusPictureItemWidth + WBStatusPictureItemMargin
            return CGSize(width: w, height: w)
        }
        
        let row = CGFloat((count - 1) / Int(WBStatusPictureMaxCount) + 1)
        let h = row * WBStatusPictureItemWidth + (row - 1) * WBStatusPictureItemMargin
        let w = WBStatusPictureMaxWidth
        return CGSize(width: w, height: h)
    }
///  构造函数
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        // 设置布局
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = WBStatusPictureItemMargin
        layout.minimumLineSpacing = WBStatusPictureItemMargin
        dataSource = self
        registerClass(WBStatusPictureViewCell.self, forCellWithReuseIdentifier: WBStatusPictureViewCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
// MARK: -  配图视图的数据
//var i = 0
//var j = 0
extension WBPictureView : UICollectionViewDataSource{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        i++
//        print("numberOfItemsInSection执行的次数\(i)")
        return self.statusViewModel?.thumbnailURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
         let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBStatusPictureViewCellID, forIndexPath: indexPath) as! WBStatusPictureViewCell
        cell.imageURL = statusViewModel?.thumbnailURLs![indexPath.item]
//        j++
//        print("cellForItemAtIndexPath执行的次数\(j)")
        return  cell
    }
}
private class WBStatusPictureViewCell :UICollectionViewCell{
    var imageURL:NSURL?{
        didSet {
            iconView.sd_setImageWithURL(imageURL)
        }
    }
///  构造函数
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        addSubview(iconView)
        iconView.ff_Fill(self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private let iconView:UIImageView = {
         let icon = UIImageView()
        // 设置图片的填充方式
//        UIViewContentMode.ScaleToFill 铺满 
//        UIViewContentMode.ScaleAspectFit 比例填充, 与clip配合使用
        icon.contentMode = UIViewContentMode.ScaleAspectFill
        // 剪裁图片
        icon.clipsToBounds = true
        return icon
        
    }()
}
